﻿namespace LayoutGridview.Helpers
{
    using System.Linq;

    public static class ColorHelper
    {
        public static float GetHue(float red, float green, float blue)
        {
            red = red / 255f;
            green = green / 255f;
            blue = blue / 255f;

            var min = FindMin(red, green, blue);
            var max = FindMax(red, green, blue);
            var delta = max - min;

            var H = 0f;
            var S = 0f;
            var L = ((max + min) / 2.0f);

            if (delta != 0)
            {
                if (L < 0.5f)
                    S = delta / (max + min);
                else
                    S = delta / (2.0f - max - min);

                var dr = (((max - red) / 6) + (delta / 2)) / delta;
                var dg = (((max - green) / 6) + (delta / 2)) / delta;
                var db = (((max - blue) / 6) + (delta / 2)) / delta;

                if (red == max)
                {
                    H = db - dg;
                }
                else if (green == max)
                {
                    H = (1 / 3) - db;
                }
                else if (blue == max)
                {
                    if (dg < dr)
                        H = (2 / 3) + (dg);
                    else
                        H = (float)240 / 360 + (dg - dr);
                };

                if (H < 0)
                    H += 1;
                if (H > 1)
                    H -= 1;

                H *= 360;
            }
            return H;
        }
        private static float FindMin(params float[] values) { return values.Min(); }
        private static float FindMax(params float[] values) { return values.Max(); }
    }
}
